<template>
  <div class="update-user-info-container">
    <div class="update-user-info-card">
      <div class="card-header">
        <h2>修改个人信息</h2>
      </div>
      <el-form
        :model="updateForm"
        :rules="updateRules"
        ref="updateFormRef"
        label-width="100px"
      >
        <el-form-item label="昵称">
          <el-input v-model="updateForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="updateForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
            <el-radio :label="0">保密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model.number="updateForm.age" type="number"></el-input>
        </el-form-item>
        <el-form-item label="码龄">
          <el-input
            v-model.number="updateForm.codingYears"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="updateForm.address"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="updateForm.email"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="updateForm.avatar"
              :src="updateForm.avatar"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="个人简介">
          <el-input v-model="updateForm.personalIntroduction" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="博客简介">
          <el-input v-model="updateForm.blogIntroduction" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="身份信息">
          <el-input v-model="updateForm.identityInfo"></el-input>
        </el-form-item>
        <el-form-item class="button-group">
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "UpdateUserInfo",
  data() {
    return {
      updateForm: {
        id: null,
        userId: null,
        nickname: "",
        gender: 0,
        age: null,
        codingYears: null,
        address: "",
        email: "",
        avatar: "",
        personalIntroduction: "",
        blogIntroduction: "",
        identityInfo: ""
      },
      updateRules: {
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            min: 2,
            max: 16,
            message: "昵称长度在2 - 16个字符之间",
            trigger: "blur"
          }
        ],
        email: [
          { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    this.getUserInfo();
  },
  methods: {
    async getUserInfo() {
      try {
        // 获取用户基本信息
        const userRes = await this.$axios.get("/user/info");
        if (userRes.data.code === 200) {
          if (userRes.data.data.avatar) {
            userRes.data.data.avatar = "data:image/jpeg;base64," + userRes.data.data.avatar;
          }
          this.updateForm = { ...this.updateForm, ...userRes.data.data };
          this.updateForm.userId = this.updateForm.id; // 将id赋值给userId
        } else {
          this.$message.error(userRes.data.message);
        }

        // 获取用户详细信息，使用userId
        const userId = this.updateForm.userId;
        const userInfoRes = await this.$axios.get(`/userInfo/get/${userId}`);
        if (userInfoRes.data.code === 200) {
          this.updateForm = {
            ...this.updateForm,
            ...userInfoRes.data.data
          };
        } else {
          this.$message.error(userInfoRes.data.message);
        }
      } catch (err) {
        console.error(err);
        this.$message.error("获取用户信息失败，请稍后重试");
      }
    },
    upload(option) {
      const { file } = option;
      const formData = new FormData();
      formData.append("file", file);

      // 调用后端接口
      this.$axios
        .post("/user/upload", formData, {
          headers: {
            Authorization: localStorage.getItem("token"),
            "Content-Type": "multipart/form-data"
          }
        })
        .then((res) => {
          if (res.data.code === 200) {
            // 触发 on-success 回调
            option.onSuccess(res.data);
          } else {
            option.onError(new Error(res.data.message || "上传失败"));
          }
        })
        .catch((err) => {
          option.onError(err);
        });
    },
    handleAvatarSuccess(res, file) {
      this.updateForm.avatar = res.avatarUrl;
      this.$message.success("头像上传成功");
    },
    handleAvatarError(err) {
      this.$message.error("头像上传失败");
    },
    beforeAvatarUpload(file) {
      // 允许的图片类型
      const allowedTypes = ["image/jpeg", "image/jpg", "image/png"];
      const isAllowedType = allowedTypes.includes(file.type);

      if (!isAllowedType) {
        this.$message.error("请上传JPG、JPEG或PNG格式的图片");
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片大小不能超过2MB");
        return false;
      }

      return true;
    },
    resetForm() {
      this.getUserInfo();
    },
    async submitForm() {
      this.$refs.updateFormRef.validate(async (valid) => {
        if (valid) {
          try {
            // 提取用户基本信息
            const userData = {
              id: this.updateForm.id,
              nickname: this.updateForm.nickname,
              gender: this.updateForm.gender,
              age: this.updateForm.age,
              codingYears: this.updateForm.codingYears,
              address: this.updateForm.address,
              email: this.updateForm.email,
              avatar: this.updateForm.avatar
            };

            // 提取用户详细信息
            const userInfoData = {
              id: this.updateForm.id,
              userId: this.updateForm.userId,
              personalIntroduction: this.updateForm.personalIntroduction,
              blogIntroduction: this.updateForm.blogIntroduction,
              identityInfo: this.updateForm.identityInfo
            };

            // 更新用户基本信息
            const userRes = await this.$axios.put("/user/info", userData);
            if (userRes.data.code === 200) {
              // 更新用户详细信息
              const userInfoRes = await this.$axios.put("/userInfo/update", userInfoData);
              if (userInfoRes.data.code === 200) {
                this.$message.success("修改成功");
                this.$router.push("/user/info");
              } else {
                this.$message.error(userInfoRes.data.message);
              }
            } else {
              this.$message.error(userRes.data.message);
            }
          } catch (err) {
            console.error(err);
            this.$message.error("修改失败，请稍后重试");
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.update-user-info-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 180px);
  padding: 20px;
}

.update-user-info-card {
  background-color: white;
  border-radius: 20px;
  box-shadow: -10px -10px 20px rgba(255, 255, 255, 0.8),
    10px 10px 20px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 600px;
  position: relative;
}

.card-header {
  margin-bottom: 30px;
  text-align: center;
}

.card-header h2 {
  font-size: 28px;
  color: #303133;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.avatar-uploader .el-upload:hover {
  border-color: #ffb76b;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 50%;
  object-fit: cover;
}

.button-group {
  text-align: center;
  margin-top: 30px;
}

.button-group .el-button {
  border-radius: 20px;
  height: 40px;
  transition: all 0.3s;
  padding: 0 30px;
  margin: 0 10px;
}

.button-group .el-button--primary {
  background-color: #ffb76b;
  border-color: #ffb76b;
}

.button-group .el-button--primary:hover {
  background-color: #ff9d34;
  border-color: #ff9d34;
  transform: translateY(-2px);
  box-shadow: 0 5px 10px rgba(255, 157, 52, 0.2);
}

.button-group .el-button:hover:not(.el-button--primary) {
  transform: translateY(-2px);
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}
</style>